import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom'
import { Form, Input, Button, Row, Col, message } from 'antd';
import { login, captcha, setToken, checkBind } from '../api/index.js'
import classNames from 'classnames';
import './login.scss';
import mjLoginBg from '../assets/images/mjlogin-bg.jpg';

const Login = (props) => {
  const [loginForm] = Form.useForm();
  const { history } = props
  const { saveLoginUserinfo, saveToken } = props.store
  // xtoken
  const [random, setRandom] = useState(Date.now())
  // 图片地址
  const [codeSrc, setCodeSrc] = useState('')
  // 二次验证
  const [showGoogle, setShowGoogle] = useState(false)
  // 登录
  const onFinish = async (values) => {
    console.log('Success:', values);
    try {
      let params = {
        ...values,
      }
      let res = await login(params, {
        headers: { xtoken: random },
      })
      if (res.code === 0) {
        let Permissions = []
        res.data.permissions.forEach(item=>{
          Permissions.push(item.id)
          if(item.parentId && Permissions.indexOf(item.parentId)===-1){
            Permissions.push(item.parentId)
          }
          item.children&&item.children.forEach(iitem=>{
            Permissions.push(iitem.id)
            if(iitem.parentId && Permissions.indexOf(iitem.parentId)===-1){
              Permissions.push(iitem.parentId)
            }
          })
        })
        localStorage.setItem('Permissions',Permissions)
        message.destroy()
        message.success('登录成功')
        saveLoginUserinfo(res.data)
        saveToken(res.data.sessionId)
        setToken(res.data.sessionId)
        history.push('/')
      } else {
        // 刷新验证码
        setRandom(Date.now())
      }
      console.log(res)
    } catch (error) {
      console.log(error)
    }
  };
  const getCheckBind = (values) => {
    // try {
  	 //  checkBind({
  		//   account: values.userName
  	 //  }).then((res)=>{
		  // if(res.data === true && !values.googleCode){
			 // setShowGoogle(true); 
		  // }else{
			 onFinish(values)
		 //  }
	  // })
   //  } catch (error) {
   //    console.log(error)
   //  }
  }
  const getCode = async () => {
    let res = await captcha(random)
    setCodeSrc(res)
  }
  
  // 表单错误
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 首次加载
  useEffect(() => {
    saveLoginUserinfo({})
    getCode()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [random])
  return (
    <div className="container">
      <div className={classNames(['img-left',process.env.REACT_APP_BUILDENV === 'toll' ? 'toll': ''])}>
        <img src={mjLoginBg} alt="" />
      </div>
      <div className="form-containter">
        <div className="form-box">
          <p className="form-title">
            欢迎使用168pay商户总后台
          </p>
          <Form
            labelCol={{
              span: 24,
            }}
            wrapperCol={{
              span: 24,
            }}
            form={loginForm}
            name="basic"
            initialValues={{ userName: '', pwd: '', code: '', googleCode:'' }}
            onFinish={getCheckBind}
            onFinishFailed={onFinishFailed}
            validateTrigger="onBlur"
            autoComplete="off"
            className="form-content"
          >
			<div className="showGogle" onClick={()=>{setShowGoogle(!showGoogle)}}>二次验证</div>
            <Form.Item
              label="登陆账号"
              name="userName"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="登陆密码"
              name="pwd"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password />
            </Form.Item>
			{
				showGoogle?
				<Form.Item
				  label="谷歌验证码"
				  name="googleCode"
				  rules={[{ required: true, message: '请输入谷歌验证码!' }]}
				>
				  <Input />
				</Form.Item>
				:null
			}
            <Row>
              <Col span={18}>
                <Form.Item
                  label="验证码"
                  name="code"
                  getValueFromEvent={(event) => {
                    return event.target.value.replace(/\D/g, '')
                  }}
                  rules={[
                    { required: true, message: '请输入验证码!' },
                  ]}
                >
                  <Input maxLength="4" />
                </Form.Item>
              </Col>
              <Col span={5} offset={1}>
                <div className="form-img-wrapper" onClick={() => {
                  setRandom(Date.now())
                }}>
                  <img
                    src={codeSrc}
                    alt="" />
                </div>
              </Col>
            </Row>
            <Form.Item>
              <Button type="primary" className={classNames([process.env.REACT_APP_BUILDENV === 'toll' ? 'toll': ''])} htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      <p className="copy-right">
        Copyright @ 2021 Inc. All Rights Reserved.
      </p>
    </div>
  )
}
export default withRouter(Login)